package com.fangshi

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.MenuHost
import androidx.core.view.MenuProvider
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.paging.LoadState
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import com.fangshi.adapter.RecordAdapter
import com.fangshi.databinding.FragmentRecordsBinding
import com.fangshi.viewmodels.GarageViewModelFactory
import com.fangshi.viewmodels.RecordsViewModel
import com.fangshi.viewmodels.RecordsViewModelFactory
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class RecordsFragment : Fragment() {

    private val viewModel: RecordsViewModel by viewModels(factoryProducer = {
        val baseUrl = requireActivity().getPreferences(Context.MODE_PRIVATE)
            .getString(KEY, DEFAULT_BASE_URL)
        RecordsViewModelFactory(baseUrl!!)
    })
    private lateinit var binding: FragmentRecordsBinding


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        setupMenu()
        (activity as AppCompatActivity).supportActionBar?.title = "槽车出入库记录"
        (activity as AppCompatActivity).supportActionBar?.setDisplayHomeAsUpEnabled(true)
        binding = FragmentRecordsBinding.inflate(inflater, container, false)

        val adapter = RecordAdapter()

        binding.recyclerView.adapter = adapter
        binding.recyclerView.layoutManager = LinearLayoutManager(requireContext())
        //此处必须分开两个launch，估计因为flow的suspend方法会阻塞本协程
        lifecycleScope.launch {
            viewModel.allRecord.collectLatest { adapter.submitData(it) }
        }
        lifecycleScope.launch {
            adapter.loadStateFlow.collectLatest { loadState ->
                if (loadState.refresh is LoadState.Error) {
                    val errorState = loadState.refresh as LoadState.Error
                    Toast.makeText(
                        requireContext(),
                        errorState.error.message.toString(),
                        Toast.LENGTH_LONG
                    ).show()
                }
            }

        }


        return binding.root
    }


    private fun setupMenu() {
        (requireActivity() as MenuHost).addMenuProvider(object : MenuProvider {
            override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
            }

            override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
                when (menuItem.itemId) {
                    android.R.id.home -> findNavController().navigateUp()
                }
                return true
            }
        }, viewLifecycleOwner, Lifecycle.State.RESUMED)
    }


}